package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.persistence.CartDao;
import JPetStore.persistence.impl.CartDaoImpl;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CartFormServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据数据库实时更新cart
        try{
            HttpSession session = req.getSession();
            Cart cart = (Cart)session.getAttribute("cart");
            //cart.getCartItemList().clear();//清空session遗留的cartitemlist的数据，避免看到上一个用户的购物车(在sion界面创建新cart，这里不用了)
            CartDao cartDao = new CartDaoImpl();
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            if (loginAccount != null) {
                String username = loginAccount.getUsername();
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "查看了购物车";
                logService.insertLogInfo(username, logInfo);
            }
            cartDao.getCart(loginAccount,cart.getCartItemList());//实时查看数据
            session.setAttribute("cart",cart);
        }catch (Exception e){
            e.printStackTrace();
        }
        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}
